<?php

namespace Admin\Logic;

/**
 * ModelLogic
 */
class ModelLogic extends CommonLogic {
    /**
     * 写出菜单配置
     * @param  array $menu 菜单数组
     * @return mixed
     */
    public function writeMenu(array $menu) {
        // 删除缓存
        del_dir_or_file(RUNTIME_PATH . '~runtime.php');
        return fast_cache('model_menu', $menu, APP_PATH . 'Admin/Conf/');
    }

    /**
     * 得到菜单
     * @return mixed
     */
    public function getMenu() {
        $menu = fast_cache('model_menu', '', APP_PATH . 'Admin/Conf/');
        if (!is_array($menu)) {
            return array();
        }

        return $menu;
    }

    /**
     * 添加菜单项
     * @param  array $menuItem 需要加入到菜单的菜单项
     * @return array
     */
    public function addMenuItem(array $menuItem) {
        if (is_null($menuItem)) {
            return false;
        }
        $menu = $this->getMenu();
        foreach ($menuItem['Content']['sub_menu'] as $key => $val) {
            $menu['Content']['sub_menu'][$key] = $val;
        }
        //$menu['Content']['sub_menu'] = array_merge($menu['Content']['sub_menu'], $menuItem['Content']['sub_menu']);
        $this->writeMenu($menu);
        return $menu;
    }

    /**
     * 删除菜单项
     * @param  array  $ctrlName 需要删除的菜单项名称
     * @return mixed
     */
    public function delMenuItem($id) {
        $menu = $this->getMenu();
        unset($menu["Content"]['sub_menu'][intval("10" . $id)]);

        $this->writeMenu($menu);
        return $menu;
    }

    /**
     * 替换指定的菜单项
     * @param  array  $menuItem 新菜单项
     * @param  string $ctrlName 菜单项名称
     * @return array
     */
    public function replaceMenuItem(array $menuItem, $id) {
        $menu = $this->getMenu();
        $newMenu = array();
        
        foreach ($menu['Content']['sub_menu'] as $key => $item) {
            $item_key = array_keys($item['item']);
            if ($item_key[0] == 'Content/index?id='.$id && is_array($menuItem)) {
                $menu['Content']['sub_menu'][$key]['item']['10' . $id] = $menuItem['name'];
                continue ;
            }

            //$newMenu[$key] = $item;
        }
        //print_r($menu);
        $this->writeMenu($menu);
        return $menu;
    }

    /**
     * 生成菜单项
     * @param  string $itemName  菜单名称
     * @param  int $id 模型名ID
     * @return  array            菜单数组
     */
    public function genMenuItem($itemName, $id) {
        $menu["Content"] = array(
            'sub_menu' => array(
                "10". $id => array('item' => array("Content/index?id={$id}" => $itemName))
            )
        );
        return $menu;
    }
}
